/**
 * 输入管理系统
 */
export class Input {
  private pressedKeys = new Set<string>();
  private mouseX = 0;
  private mouseY = 0;
  private mousePressed = false;

  constructor(target: Window | HTMLElement = window) {
    // 键盘事件 - 始终监听window以确保能捕获到键盘事件
    window.addEventListener('keydown', (e) => {
      const keyEvent = e as KeyboardEvent;
      this.pressedKeys.add(keyEvent.key.toLowerCase());
      // 只阻止游戏相关按键的默认行为
      if (['w', 'a', 's', 'd', ' ', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(keyEvent.key)) {
        e.preventDefault();
      }
    });

    window.addEventListener('keyup', (e) => {
      const keyEvent = e as KeyboardEvent;
      this.pressedKeys.delete(keyEvent.key.toLowerCase());
      // 只阻止游戏相关按键的默认行为
      if (['w', 'a', 's', 'd', ' ', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(keyEvent.key)) {
        e.preventDefault();
      }
    });

    // 鼠标事件
    if (target instanceof HTMLElement) {
      target.addEventListener('mousemove', (e) => {
        const rect = target.getBoundingClientRect();
        this.mouseX = e.clientX - rect.left;
        this.mouseY = e.clientY - rect.top;
      });

      target.addEventListener('mousedown', () => {
        this.mousePressed = true;
      });

      target.addEventListener('mouseup', () => {
        this.mousePressed = false;
      });
    }

    // 防止右键菜单
    target.addEventListener('contextmenu', (e) => e.preventDefault());
  }

  /**
   * 检查按键是否被按下
   */
  isKeyPressed(key: string): boolean {
    return this.pressedKeys.has(key.toLowerCase());
  }

  /**
   * 获取水平轴输入 (-1 到 1)
   */
  getHorizontalAxis(): number {
    const left = this.isKeyPressed('arrowleft') || this.isKeyPressed('a');
    const right = this.isKeyPressed('arrowright') || this.isKeyPressed('d');
    return (right ? 1 : 0) - (left ? 1 : 0);
  }

  /**
   * 获取垂直轴输入 (-1 到 1)
   */
  getVerticalAxis(): number {
    const up = this.isKeyPressed('arrowup') || this.isKeyPressed('w');
    const down = this.isKeyPressed('arrowdown') || this.isKeyPressed('s');
    return (down ? 1 : 0) - (up ? 1 : 0);
  }

  /**
   * 检查射击键是否被按下
   */
  isFirePressed(): boolean {
    return this.isKeyPressed(' ') || this.isKeyPressed('enter') || this.mousePressed;
  }

  /**
   * 获取鼠标位置
   */
  getMousePosition(): { x: number; y: number } {
    return { x: this.mouseX, y: this.mouseY };
  }
}